package com.cmdb.web.controller.system;

import com.cmdb.common.annotation.Log;
import com.cmdb.common.core.controller.BaseController;
import com.cmdb.common.core.domain.AjaxResult;
import com.cmdb.common.core.domain.entity.SysDept;
import com.cmdb.common.core.page.TableDataInfo;
import com.cmdb.common.enums.BusinessType;
import com.cmdb.common.utils.SecurityUtils;
import com.cmdb.system.domain.SysFiles;
import com.cmdb.system.domain.SysSms;
import com.cmdb.system.domain.SysSmsDeatil;
import com.cmdb.system.mapper.SysFileMapper;
import com.cmdb.system.service.ISysSmsDeatilService;
import com.cmdb.system.service.ISysSmsService;
import com.cmdb.web.config.MiniosProperties;
import io.minio.GetObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * smsjobController
 *
 * @author cyq
 * @date 2025-06-14
 */
@RestController
@Slf4j
@RequestMapping("/system/smsjob")
public class SysSmsController extends BaseController
{
    @Autowired
    private ISysSmsService sysSmsService;

    @Autowired
    private ISysSmsDeatilService sysSmsDeatilService;

    @Autowired
    private io.minio.MinioClient minioClient;

    @Autowired
    private MiniosProperties miniosProperties;

    @Autowired
    private SysFileMapper fileMapper;

    @Autowired
    private com.cmdb.system.service.ISysDeptService sysDeptService;

    /**
     * 查询smsjob列表
     */
    @PreAuthorize("@ss.hasPermi('system:smsjob:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysSms sysSms)
    {
        startPage();
        boolean admin = SecurityUtils.isAdmin(SecurityUtils.getUserId());
        if(!admin){
            Long deptId = SecurityUtils.getDeptId();
            sysSms.setDeptId(SecurityUtils.getDeptId()+"");
        }
        List<SysSms> list = sysSmsService.selectSysSmsList(sysSms);
        return getDataTable(list);
    }

    @GetMapping("/list/job")
    public Integer listJob(SysSms sysSms)
    {
        sysSms.setStatus("Y");
        boolean admin = SecurityUtils.isAdmin(SecurityUtils.getUserId());
        if(!admin){
            Long deptId = SecurityUtils.getDeptId();
            sysSms.setDeptId(SecurityUtils.getDeptId()+"");
        }else{
            return  0;
        }
        int cou  = sysSmsService.selectSysSmsListJob(sysSms);
        return  cou;
    }

    /**
     * 获取smsjob详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:smsjob:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id)
    {
        return AjaxResult.success(sysSmsService.selectSysSmsById(id));
    }

    /**
     * 新增smsjob
     */
    @PreAuthorize("@ss.hasPermi('system:smsjob:add')")
    @Log(title = "smsjob", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysSms sysSms)
    {

        return toAjax(sysSmsService.insertSysSms(sysSms));
    }

    /**
     * 修改smsjob
     */
    @PreAuthorize("@ss.hasPermi('system:smsjob:edit')")
    @Log(title = "smsjob", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysSms sysSms)
    {
        return toAjax(sysSmsService.updateSysSms(sysSms));
    }

    /**
     * 删除smsjob
     */
    @PreAuthorize("@ss.hasPermi('system:smsjob:remove')")
    @Log(title = "smsjob", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(sysSmsService.deleteSysSmsByIds(ids));
    }

    /**
     * 导出smsjob列表（带附件）- 高性能模式
     */
    @PreAuthorize("@ss.hasPermi('system:smsjob:export')")
    @Log(title = "smsjob", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysSms sysSms, @RequestParam(required = false) String ids) throws IOException
    {
        List<SysSms> list;

        // 如果传入了ids参数，则导出指定的数据
        if (ids != null && !ids.isEmpty()) {
            String[] idArray = ids.split(",");
            List<Long> idList = new ArrayList<>();
            for (String id : idArray) {
                try {
                    idList.add(Long.parseLong(id.trim()));
                } catch (NumberFormatException e) {
                    // 忽略无效的ID
                }
            }
            if (!idList.isEmpty()) {
                list = sysSmsService.selectSysSmsByIds(idList);
            } else {
                list = new ArrayList<>();
            }
        } else {
            // 否则导出所有符合条件的数据
            boolean admin = SecurityUtils.isAdmin(SecurityUtils.getUserId());
            if(!admin){
                Long deptId = SecurityUtils.getDeptId();
                sysSms.setDeptId(SecurityUtils.getDeptId()+"");
            }
            list = sysSmsService.selectSysSmsList(sysSms);
        }

        // 高性能优化：批量获取任务详情，避免N+1查询
        if (!list.isEmpty()) {
            // 使用现有的查询方法，逐个查询但优化内存使用
            Map<Long, List<SysSmsDeatil>> detailsMap = new HashMap<>();

            for (SysSms sms : list) {
                SysSmsDeatil queryParam = new SysSmsDeatil();
                queryParam.setDataId(sms.getId());
                List<SysSmsDeatil> details = sysSmsDeatilService.selectSysSmsDeatilList(queryParam);
                detailsMap.put(sms.getId(), details);
                sms.setSmsDeatils(details);
            }
        }

        log.info("开始导出任务数据，任务数量: " + list.size());
        log.info("MinIO配置信息 - Bucket: " + miniosProperties.getBucketName());

        // 设置响应头
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment; filename=\"任务下发数据_" + System.currentTimeMillis() + ".zip\"");

        // 高性能优化：使用缓冲流和批量处理
        try (ZipOutputStream zipOut = new ZipOutputStream(new java.io.BufferedOutputStream(response.getOutputStream()))) {
            // 设置压缩级别
            zipOut.setLevel(java.util.zip.Deflater.BEST_SPEED);

            // 1. 预先获取部门映射，避免重复查询
            Map<String, String> deptMap = getDeptNameMap();

            // 2. 格式化回复信息（批量处理）
            formatReplyInfoBatch(list);

            // 3. 创建Excel文件（使用流式处理）
            createExcelFiles(zipOut, list, deptMap);

            // 4. 批量处理附件（使用线程池和流式下载）
            processAttachmentsBatch(zipOut, list);
        }
    }

    /**
     * 批量格式化回复信息
     */
    private void formatReplyInfoBatch(List<SysSms> list) {
        for (SysSms sms : list) {
            List<SysSmsDeatil> deatils = sms.getSmsDeatils();
            if (deatils != null && !deatils.isEmpty()) {
                StringBuilder replyBuilder = new StringBuilder();
                for (int i = 0; i < deatils.size(); i++) {
                    SysSmsDeatil deatil = deatils.get(i);
                    replyBuilder.append("回复").append(i + 1).append(": ");
                    if (deatil.getUser() != null) {
                        replyBuilder.append("用户[").append(deatil.getUser()).append("] ");
                    }
                    if (deatil.getContent() != null) {
                        replyBuilder.append(deatil.getContent());
                    }
                    if (deatil.getCreateTime() != null) {
                        replyBuilder.append(" (时间:").append(formatDateTime(deatil.getCreateTime())).append(")");
                    }
                    if (i < deatils.size() - 1) {
                        replyBuilder.append("\n");
                    }
                }
                sms.setReplyInfo(replyBuilder.toString());
            } else {
                sms.setReplyInfo("暂无回复");
            }
        }
    }

    /**
     * 创建Excel文件（流式处理）
     */
    private void createExcelFiles(ZipOutputStream zipOut, List<SysSms> list, Map<String, String> deptMap) throws IOException {
        // 创建包含多个Sheet的Excel文件
        try (ByteArrayOutputStream multiSheetExcelStream = new ByteArrayOutputStream()) {
            // 创建工作簿
            org.apache.poi.ss.usermodel.Workbook workbook = new org.apache.poi.xssf.usermodel.XSSFWorkbook();

            // Sheet1: 任务主表数据
            org.apache.poi.ss.usermodel.Sheet taskSheet = workbook.createSheet("任务主表");
            createTaskSheetOptimized(taskSheet, list, deptMap);

            // Sheet2: 任务回复数据
            org.apache.poi.ss.usermodel.Sheet replySheet = workbook.createSheet("任务回复");
            createReplySheetOptimized(replySheet, list);

            // Sheet3: 任务与回复关联视图
            org.apache.poi.ss.usermodel.Sheet summarySheet = workbook.createSheet("任务汇总");
            createSummarySheetOptimized(summarySheet, list, deptMap);

            // 写入Excel文件
            workbook.write(multiSheetExcelStream);
            workbook.close();

            ZipEntry multiSheetExcelEntry = new ZipEntry("任务下发数据_完整版.xlsx");
            zipOut.putNextEntry(multiSheetExcelEntry);
            zipOut.write(multiSheetExcelStream.toByteArray());
            zipOut.closeEntry();
        }
    }

    /**
     * 批量处理附件（调试版本 - 同步处理）
     */
    private void processAttachmentsBatch(ZipOutputStream zipOut, List<SysSms> list) throws IOException {
        // 统计附件信息
        int totalFiles = 0;
        int processedFiles = 0;
        int failedFiles = 0;

        // 收集所有需要下载的文件
        List<FileDownloadTask> downloadTasks = new ArrayList<>();

        for (SysSms sms : list) {
            List<SysSmsDeatil> deatils = sms.getSmsDeatils();
            if (deatils != null) {
                for (SysSmsDeatil deatil : deatils) {
                    if (deatil.getFileList() != null) {
                        for (SysFiles file : deatil.getFileList()) {
                            // 检查文件信息，fileName或filePath任一不为空即可
                            if ((file.getFileName() != null && !file.getFileName().trim().isEmpty()) ||
                                (file.getFilePath() != null && !file.getFilePath().trim().isEmpty())) {
                                downloadTasks.add(new FileDownloadTask(file, sms));
                                totalFiles++;
                                log.info("添加下载任务 - 任务ID: " + sms.getId() +
                                                 ", fileName: " + file.getFileName() +
                                                 ", filePath: " + file.getFilePath());
                            }
                        }
                    }
                }
            }
        }

        log.info("开始处理附件，总计文件数: " + totalFiles);

        if (downloadTasks.isEmpty()) {
            log.info("没有找到需要下载的附件");
            return;
        }

        // 同步处理文件下载（调试版本）
        for (FileDownloadTask task : downloadTasks) {
            try {
                AttachmentData attachmentData = downloadFile(task.file, task.sms);
                if (attachmentData != null && attachmentData.data != null) {
                    ZipEntry fileEntry = new ZipEntry(attachmentData.zipPath);
                    zipOut.putNextEntry(fileEntry);
                    zipOut.write(attachmentData.data);
                    zipOut.closeEntry();
                    processedFiles++;
                    log.info("成功处理附件: " + attachmentData.zipPath);
                } else {
                    failedFiles++;
                    log.info("附件下载失败: 返回数据为空");
                }
            } catch (Exception e) {
                failedFiles++;
                log.error("处理附件失败: " + e.getMessage());
                e.printStackTrace();
            }
        }

        log.info("附件处理完成 - 总计: " + totalFiles + ", 成功: " + processedFiles + ", 失败: " + failedFiles);
    }

    /**
     * 文件下载任务类
     */
    private static class FileDownloadTask {
        final SysFiles file;
        final SysSms sms;

        FileDownloadTask(SysFiles file, SysSms sms) {
            this.file = file;
            this.sms = sms;
        }
    }

    /**
     * 下载单个文件
     */
    private AttachmentData downloadFile(SysFiles file, SysSms sms) {
        String fileName = file.getFileName();
        String filePath = file.getFilePath();

        log.info("开始下载文件 - fileName: " + fileName + ", filePath: " + filePath);

        try {
            // 确定要使用的文件标识符
            String objectName = null;

            // 策略1：如果fileName是UUID格式（32位十六进制），直接使用
            if (fileName != null && fileName.matches("[a-f0-9]{32}\\.[a-zA-Z0-9]+")) {
                objectName = fileName.trim();
                log.info("使用UUID文件名: " + objectName);
            }
            // 策略2：从filePath中提取UUID文件名
            else if (filePath != null && !filePath.trim().isEmpty()) {
                String url = filePath.trim();
                if (url.contains("/")) {
                    String extractedName = url.substring(url.lastIndexOf("/") + 1);
                    // 移除URL参数
                    if (extractedName.contains("?")) {
                        extractedName = extractedName.substring(0, extractedName.indexOf("?"));
                    }

                    // 检查提取的名称是否是UUID格式
                    if (extractedName.matches("[a-f0-9]{32}\\.[a-zA-Z0-9]+")) {
                        objectName = extractedName;
                        log.info("从URL提取UUID文件名: " + objectName);
                    } else {
                        // 如果不是UUID格式，可能是原始文件名，尝试在MinIO中查找
                        log.info("提取的文件名不是UUID格式，尝试查找: " + extractedName);
                        objectName = extractedName;
                    }
                }
            }
            // 策略3：如果fileName不是UUID格式，直接使用（可能是原始文件名）
            else if (fileName != null && !fileName.trim().isEmpty()) {
                objectName = fileName.trim();
                log.info("使用原始文件名: " + objectName);
            }

            if (objectName == null) {
                log.error("文件标识符为空，跳过下载 - fileName: " + fileName + ", filePath: " + filePath);
                return null;
            }

            log.info("最终使用文件标识符: " + objectName);

            // 从MinIO下载文件
            InputStream fileStream = minioClient.getObject(
                GetObjectArgs.builder()
                    .bucket(miniosProperties.getBucketName())
                    .object(objectName)
                    .build());

            if (fileStream != null) {
                // 使用缓冲流提高性能
                try (java.io.BufferedInputStream bufferedStream = new java.io.BufferedInputStream(fileStream);
                     ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {

                    byte[] buffer = new byte[8192]; // 8KB缓冲区
                    int length;
                    int totalBytes = 0;
                    while ((length = bufferedStream.read(buffer)) > 0) {
                        outputStream.write(buffer, 0, length);
                        totalBytes += length;
                    }

                    byte[] fileData = outputStream.toByteArray();
                    log.info("文件下载成功: " + objectName + ", 大小: " + totalBytes + " 字节");

                    // 确定ZIP中的显示文件名
                    String displayFileName = getDisplayFileName(file);

                    String folderName = sms.getId() + "_" + (sms.getTitle() != null ? sms.getTitle().replaceAll("[\\\\/:*?\"<>|]", "_") : "未命名");
                    String zipEntryName = "附件/" + folderName + "/" + displayFileName;

                    return new AttachmentData(zipEntryName, fileData);
                }
            } else {
                log.error("MinIO返回的文件流为空: " + objectName);
            }
        } catch (Exception e) {
            log.error("下载文件失败: " + (fileName != null ? fileName : filePath) + ", 错误: " + e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取显示文件名
     */
    private String getDisplayFileName(SysFiles file) {
        String fileName = file.getFileName();
        String filePath = file.getFilePath();

        // 如果fileName是UUID格式（32位十六进制），尝试从filePath中获取原始文件名
        if (fileName != null && fileName.matches("[a-f0-9]{32}\\.[a-zA-Z0-9]+")) {
            // fileName是UUID格式，尝试从filePath中提取原始文件名
            if (filePath != null && filePath.contains("/")) {
                String originalName = filePath.substring(filePath.lastIndexOf("/") + 1);
                if (originalName.contains("?")) {
                    originalName = originalName.substring(0, originalName.indexOf("?"));
                }
                // 如果提取的名称不是UUID格式，使用它
                if (!originalName.matches("[a-f0-9]{32}\\.[a-zA-Z0-9]+")) {
                    return originalName;
                }
            }
        }

        // 否则使用fileName，如果fileName为空则使用filePath的最后部分
        if (fileName != null && !fileName.trim().isEmpty()) {
            return fileName;
        } else if (filePath != null && filePath.contains("/")) {
            String name = filePath.substring(filePath.lastIndexOf("/") + 1);
            if (name.contains("?")) {
                name = name.substring(0, name.indexOf("?"));
            }
            return name;
        }

        return "未知文件";
    }

    /**
     * 附件数据类
     */
    private static class AttachmentData {
        final String zipPath;
        final byte[] data;

        AttachmentData(String zipPath, byte[] data) {
            this.zipPath = zipPath;
            this.data = data;
        }
    }

    /**
     * 创建任务主表Sheet（优化版本）
     */
    private void createTaskSheetOptimized(org.apache.poi.ss.usermodel.Sheet sheet, List<SysSms> list, Map<String, String> deptMap) {
        // 创建标题行
        org.apache.poi.ss.usermodel.Row headerRow = sheet.createRow(0);
        String[] headers = {"任务ID", "标题", "内容", "部门名称", "状态", "创建时间", "创建人", "回复数量"};

        for (int i = 0; i < headers.length; i++) {
            org.apache.poi.ss.usermodel.Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
        }

        // 填充数据行
        int rowNum = 1;
        for (SysSms sms : list) {
            org.apache.poi.ss.usermodel.Row row = sheet.createRow(rowNum++);

            row.createCell(0).setCellValue(sms.getId());
            row.createCell(1).setCellValue(sms.getTitle() != null ? sms.getTitle() : "");
            row.createCell(2).setCellValue(sms.getContent() != null ? sms.getContent() : "");
            row.createCell(3).setCellValue(getDeptName(sms.getDeptId(), deptMap));
            row.createCell(4).setCellValue(sms.getStatus() != null ? sms.getStatus() : "");
            row.createCell(5).setCellValue(formatDateTime(sms.getCreateTime()));
            row.createCell(6).setCellValue(sms.getCreateBy() != null ? sms.getCreateBy() : "");

            // 计算回复数量
            int replyCount = sms.getSmsDeatils() != null ? sms.getSmsDeatils().size() : 0;
            row.createCell(7).setCellValue(replyCount);
        }

        // 自动调整列宽
        for (int i = 0; i < headers.length; i++) {
            sheet.autoSizeColumn(i);
        }
    }

    /**
     * 创建任务回复Sheet（优化版本）
     */
    private void createReplySheetOptimized(org.apache.poi.ss.usermodel.Sheet sheet, List<SysSms> list) {
        // 创建标题行
        org.apache.poi.ss.usermodel.Row headerRow = sheet.createRow(0);
        String[] headers = {"任务ID", "任务标题", "回复ID", "回复内容", "回复用户", "回复时间", "附件数量"};

        for (int i = 0; i < headers.length; i++) {
            org.apache.poi.ss.usermodel.Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
        }

        // 填充数据行
        int rowNum = 1;
        for (SysSms sms : list) {
            List<SysSmsDeatil> deatils = sms.getSmsDeatils();
            if (deatils != null && !deatils.isEmpty()) {
                for (SysSmsDeatil deatil : deatils) {
                    org.apache.poi.ss.usermodel.Row row = sheet.createRow(rowNum++);

                    row.createCell(0).setCellValue(sms.getId());
                    row.createCell(1).setCellValue(sms.getTitle() != null ? sms.getTitle() : "");
                    row.createCell(2).setCellValue(deatil.getId() != null ? deatil.getId().toString() : "");
                    row.createCell(3).setCellValue(deatil.getContent() != null ? deatil.getContent() : "");
                    row.createCell(4).setCellValue(deatil.getUser() != null ? deatil.getUser() : "");
                    row.createCell(5).setCellValue(formatDateTime(deatil.getCreateTime()));

                    // 计算附件数量
                    int fileCount = deatil.getFileList() != null ? deatil.getFileList().size() : 0;
                    row.createCell(6).setCellValue(fileCount);
                }
            } else {
                // 如果没有回复，也显示一行
                org.apache.poi.ss.usermodel.Row row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(sms.getId());
                row.createCell(1).setCellValue(sms.getTitle() != null ? sms.getTitle() : "");
                row.createCell(2).setCellValue("");
                row.createCell(3).setCellValue("暂无回复");
                row.createCell(4).setCellValue("");
                row.createCell(5).setCellValue("");
                row.createCell(6).setCellValue(0);
            }
        }

        // 自动调整列宽
        for (int i = 0; i < headers.length; i++) {
            sheet.autoSizeColumn(i);
        }
    }

    /**
     * 创建任务汇总Sheet（优化版本）
     */
    private void createSummarySheetOptimized(org.apache.poi.ss.usermodel.Sheet sheet, List<SysSms> list, Map<String, String> deptMap) {
        // 创建标题行
        org.apache.poi.ss.usermodel.Row headerRow = sheet.createRow(0);
        String[] headers = {"任务ID", "任务标题", "任务内容", "部门", "状态", "创建时间", "回复数量", "附件数量", "最新回复时间", "最新回复用户"};

        for (int i = 0; i < headers.length; i++) {
            org.apache.poi.ss.usermodel.Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
        }

        // 填充数据行
        int rowNum = 1;
        for (SysSms sms : list) {
            org.apache.poi.ss.usermodel.Row row = sheet.createRow(rowNum++);

            row.createCell(0).setCellValue(sms.getId());
            row.createCell(1).setCellValue(sms.getTitle() != null ? sms.getTitle() : "");
            row.createCell(2).setCellValue(sms.getContent() != null ? sms.getContent() : "");
            row.createCell(3).setCellValue(getDeptName(sms.getDeptId(), deptMap));
            row.createCell(4).setCellValue(sms.getStatus() != null ? sms.getStatus() : "");
            row.createCell(5).setCellValue(formatDateTime(sms.getCreateTime()));

            List<SysSmsDeatil> deatils = sms.getSmsDeatils();
            int replyCount = deatils != null ? deatils.size() : 0;
            row.createCell(6).setCellValue(replyCount);

            // 计算总附件数量
            int totalFileCount = 0;
            if (deatils != null) {
                for (SysSmsDeatil deatil : deatils) {
                    if (deatil.getFileList() != null) {
                        totalFileCount += deatil.getFileList().size();
                    }
                }
            }
            row.createCell(7).setCellValue(totalFileCount);

            // 最新回复信息
            if (deatils != null && !deatils.isEmpty()) {
                // 按创建时间排序，获取最新回复
                deatils.sort((a, b) -> {
                    if (a.getCreateTime() == null) return 1;
                    if (b.getCreateTime() == null) return -1;
                    return b.getCreateTime().compareTo(a.getCreateTime());
                });

                SysSmsDeatil latestReply = deatils.get(0);
                row.createCell(8).setCellValue(formatDateTime(latestReply.getCreateTime()));
                row.createCell(9).setCellValue(latestReply.getUser() != null ? latestReply.getUser() : "");
            } else {
                row.createCell(8).setCellValue("");
                row.createCell(9).setCellValue("暂无回复");
            }
        }

        // 自动调整列宽
        for (int i = 0; i < headers.length; i++) {
            sheet.autoSizeColumn(i);
        }
    }

    /**
     * 格式化时间为 yyyy-MM-dd HH:mm:ss 格式
     */
    private String formatDateTime(Date date) {
        if (date == null) {
            return "";
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(date);
    }

    /**
     * 获取部门名称映射
     */
    private Map<String, String> getDeptNameMap() {
        Map<String, String> deptMap = new HashMap<>();
        try {
            List<SysDept> deptList = sysDeptService.selectDeptList(new SysDept());
            for (SysDept dept : deptList) {
                deptMap.put(dept.getDeptId().toString(), dept.getDeptName());
            }
        } catch (Exception e) {
            log.error("获取部门信息失败: " + e.getMessage());
        }
        return deptMap;
    }

    /**
     * 根据部门ID获取部门名称
     */
    private String getDeptName(String deptId, Map<String, String> deptMap) {
        if (deptId == null || deptId.isEmpty()) {
            return "";
        }

        // 如果deptId包含多个ID（逗号分隔），则全部转换
        if (deptId.contains(",")) {
            String[] deptIds = deptId.split(",");
            StringBuilder result = new StringBuilder();
            for (int i = 0; i < deptIds.length; i++) {
                String name = deptMap.get(deptIds[i].trim());
                if (name != null) {
                    if (i > 0) result.append("，");
                    result.append(name);
                } else {
                    if (i > 0) result.append("，");
                    result.append(deptIds[i].trim());
                }
            }
            return result.toString();
        } else {
            String name = deptMap.get(deptId.trim());
            return name != null ? name : deptId;
        }
    }
}
